package com.tairan.chapter.security.config;

import com.alibaba.fastjson.JSON;
import com.tairan.chapter.security.model.User;
import com.tairan.chapter.security.service.impl.UserServiceImpl;
import com.tairan.chapter.security.util.JwtTokenUtils;
import com.tairan.chapter.security.web.ResultEntity;
import com.tairan.chapter.security.web.ResultStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
//@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 加入自定义的安全认证
        auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 去掉 CSRF
        http.csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 使用 JWT，关闭token

                .and()
                .httpBasic().authenticationEntryPoint((request, response, e) -> {
                    e.printStackTrace();
                    response.getWriter().write(JSON.toJSONString(ResultEntity.build(ResultStatus.NEED_AUTHORITIES)));
                })

                .and()
                .authorizeRequests()
                .anyRequest()
                .access("@rbacAuthorityService.hasPermission(request, authentication)")

                .and()
                .formLogin()
                .successHandler((request, response, auth) -> {
                    User user = (User)auth.getPrincipal();
                    String jwtToken = JwtTokenUtils.generateToken(user.getUsername(), 300, "_secret");
                    response.getWriter().write(JSON.toJSONString(ResultEntity.buildSuccess(jwtToken)));
                })
                .failureHandler((request, response, e) -> {
                    e.printStackTrace();
                    response.getWriter().write(JSON.toJSONString(ResultEntity.build(ResultStatus.LOGIN_FAILED)));
                })
                .permitAll()

                .and()
                .logout()
                .logoutSuccessHandler((request, response, auth) -> {
                    response.getWriter().write(JSON.toJSONString(ResultEntity.buildSuccess()));
                })
                .permitAll();

        // 记住我
        http.rememberMe().rememberMeParameter("remember-me")
                .userDetailsService(userService).tokenValiditySeconds(300);

        http.exceptionHandling().accessDeniedHandler((request, response, e) -> {
            e.printStackTrace();
            response.getWriter().write(JSON.toJSONString(ResultEntity.build(ResultStatus.AUTHORITIES_FAILED)));
        });// 无权访问 JSON 格式的数据

        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);// JWT Filter
    }
}
